﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using DataLayer.Infrastructure;
using ModelLayer;

namespace BusinessLayer
{
    public class OrderManager
    {

        public IEnumerable<Order> GetAllOrders()
        {
            using (var uow = new UnitOfWork())
            {
                return uow.OrderRepo.Get();
            }
        }

        public IEnumerable<Order> GetByUser(long userId)
        {
            using (var uow = new UnitOfWork())
            {
                return uow.OrderRepo.Get(x => x.UserId == userId);
            }
        }

        public Order GetById(long orderId)
        {
            using (var uow = new UnitOfWork())
            {
                return uow.OrderRepo.Get(x => x.OrderId == orderId).FirstOrDefault();
            }
        }

        public bool AddUpdate(Order order)
        {
            using (var uow = new UnitOfWork())
            {
                using (var ts = new TransactionScope())
                {
                    if (order.OrderId > 0)
                    {
                        uow.OrderRepo.Update(order);
                    }
                    else
                    {

                        uow.OrderRepo.Insert(order);
                        var userCarts = uow.UserCartRepo.Get(x => x.UserId == order.UserId);
                        foreach (var userCart in userCarts)
                        {
                            uow.UserCartRepo.Delete(userCart);
                        }
                    }
                    var affectedRecords = uow.SaveChanges();
                    ts.Complete();
                    return affectedRecords > 0;
                }
            }
        }

        public bool Delete(long orderId)
        {
            using (var uow = new UnitOfWork())
            {
                var order = uow.OrderRepo.GetById(orderId);
                uow.OrderRepo.Delete(order);

                return uow.SaveChanges() > 0;
            }
        }
    }
}
